<?php

namespace Beerus\Modules\BlindBox\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\brand\Brand as mBrand;
use Biz\model\brandActivity\BlindBoxActivity as mBlindBoxActivity;
use Biz\model\brandActivity\BlindBoxActivityPrize as mBlindBoxActivityPrize;
use Biz\model\brandActivity\BrandActivityBasic;
use Biz\service\brand\BlindBox;
use Biz\service\brand\Brand;
use Biz\service\brand\BrandActivity;
use Biz\service\BrandRights\BrandEquityVerificationService;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class IndexController extends Controller
{
    const PAGE_SIZE = 20;
    const SOURCE_CATEGORY_LIST = '/admin/extend/category/child';

    const STATE_MAP = [
        0 => '待审核',
        1 => '审核通过',
        2 => '审核不通过',
    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        Admin::style('.span-label{margin-bottom: 5px; cursor: pointer; margin-right: 5px; display: inline-block;}');
        Admin::script($this->operateScript());
        if (is_null($request->input('activity_state'))) {
            $request->merge([
                'activity_state' => mBlindBoxActivity::ACTIVITY_STATE_NORMAL
            ]);
        }
        $request_data = $request->all();
        $condition = self::getCondition($request_data);
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        if (!is_null($condition)) {
            $where = $condition;
            $where['LIMIT'] = [
                ($page - 1) * $page_size,
                $page_size
            ];
            $result = self::getBlindBoxList($where);
        } else {
            $result = ['list' => [], 'total' => 0];
        }
        $gridModel = new pGridDataModel($result['list'], $result['total'], [
            'perPage' => $page_size
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->dropDown('brand_value', [
                            'brand_id' => '品牌ID',
                            'brand_name' => '品牌名称',
                        ]);
                        $filter->dropDown('activity_value', [
                            'activity_id' => '活动ID',
                            'activity_title' => '活动名称',
                        ]);
                    });
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('activity_state', '活动状态')->select(mBlindBoxActivity::$activityStateDesc);
                        $filter->date('start_time', '上线时间');
                    });
                    $filter->expand();
                });
                $grid->column("id", '活动ID')->width(80);
                $grid->column('title', '活动名称')->width(120);
                $grid->column('brand_id', '品牌')->display(function () {
                    $html = '<ul class="list-inline">';
                    $html .= '<li>ID：' . $this->brand_id . '</li>';
                    $html .= '<li>名称：' . $this->brand_name . '</li>';
                    $html .= '</ul>';
                    return $html;
                })->style('min-width:120px');
                $grid->column('prize_type', '奖品类型')->display(function () {
                    $html = '<ul class="list-unstyled">';
                    $html .= '<li>奖品类型：<b>' . mBlindBoxActivity::$prizeTypeDesc[$this->prize_type] . '</b></li>';
                    switch ($this->prize_type) {
                        case mBlindBoxActivity::PRIZE_TYPE_GOODS:
                            $h5Url = HhzEnv::detectShopDomain() . 'shop/goods-detail/wiki?basic_id=' . $this->basic_id . '&no-pc-redirect=true';
                            $html .= '<li>WIKI ID：<a class="fa" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $h5Url . '\'
                            });">' . $this->basic_id . '</a></li>';
                            $html .= '<li>奖品名称：' . $this->prize_title . '</li>';
                            $html .= '<li><a href="/admin/blindBox/index/' . $this->id . '/editImg">更换奖品图片</a></li>';
                            break;
                        case mBlindBoxActivity::PRIZE_TYPE_SHOP_COUPON:
                            $html .= '<li>奖品名称：' . $this->prize_title . '</li>';
                            $html .= '<li>店铺名称：' . $this->shop_name . '</li>';
                            $html .= '<li>优惠券码：</li>';
                            foreach ($this->coupon as $item) {
                                $html .= '<li style="color: #00a65a ">';
                                $html .= '<a href="javascript:void(0);" class="grid-column-copyable text-muted" data-content="' . $item . '" title="Copied!" data-placement="bottom"><i class="fa fa-copy"></i></a>';
                                $html .= '「' . $item . '」</li>';
                            }
                            $html .= '<li><a href="/admin/blindBox/index/' . $this->id . '/editCoupon">编辑优惠券</a></li>';
                            break;
                        case mBlindBoxActivity::PRIZE_TYPE_GOOD_COUPON:
                            $h5Url = HhzEnv::detectShopDomain() . 'shop/goods-detail/wiki?basic_id=' . $this->basic_id . '&no-pc-redirect=true';
                            $html .= '<li>WIKI ID：<a class="fa" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $h5Url . '\'
                            });">' . $this->basic_id . '</a></li>';
                            $html .= '<li>奖品名称：' . $this->prize_title . '</li>';
                            $html .= '<li>店铺名称：' . $this->shop_name . '</li>';
                            $html .= '<li>优惠券码：</li>';
                            foreach ($this->coupon as $item) {
                                $html .= '<li style="color: #00a65a ">';
                                $html .= '<a href="javascript:void(0);" class="grid-column-copyable text-muted" data-content="' . $item . '" title="Copied!" data-placement="bottom"><i class="fa fa-copy"></i></a>';
                                $html .= '「' . $item . '」</li>';
                            }
                            $html .= '<li><a href="/admin/blindBox/index/' . $this->id . '/editCoupon" >编辑优惠券</a></li>';
                            $html .= '<li><a href="/admin/blindBox/index/' . $this->id . '/editImg">更换奖品图片</a></li>';
                            break;
                    }
                    $html .= '</ul>';
                    return $html;
                })->style('min-width:190px');
                $grid->column('prize_img', '奖品图片')->display(function ($img_url) {
                    return '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'800px\', \'600px\'],content: \'' . $img_url . '\'});">
                                <img width="100px" height="100px" src="' . $img_url . '">
                            </a>';
                });
                $grid->column('screen_capture', '奖品截图')->display(function ($img_url) {
                    return '<a href="javascript:layer.open({type: 2,title: \'预览\',maxmin: true,area: [\'1080px\', \'720px\'],content: \'' . $img_url . '\'});">
                                <img width="100px" height="100px" src="' . $img_url . '">
                            </a>';
                });

                $grid->column('dynamic_img', '中奖动态')->display(function () {
                    $img = BrandActivity::getActivityDynamicImg(BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX, $this->dynamic_img);
                    $str = '<span style="color: red;font-weight: bolder;font-size: medium">添加动态图</span>';
                    $html = '<ul class="list-inline">';
                    if ($this->dynamic_img) {
                        $html .= '<img src="' . $img . '" style="max-width:100px;max-height:100px" class="img img-thumbnail">';
                        $str = '更改动态图';
                    }
                    $html .= '<li><a href="/admin/blindBox/index/' . $this->id . '/editDynamic">' . $str . '</a></li>';
                    $html .= '</ul>';
                    return $html;
                });
                $grid->column('prize_num', '奖品数量')->width(100);
                $grid->column('prize_price', '单个奖品价值')->width(120);
                $grid->column('prize_total_price', '奖品总价值')->width(100);
                $grid->column('activity_state', '活动状态')->display(function () {
                    return mBlindBoxActivity::$activityStateDesc[$this->activity_state];
                })->width(100);
                $grid->column('prize_stock', '剩余奖品数量')->width(80);
                $grid->column('start_time', '排期')->display(function () {
                    $html = '<div class="span-label">';
                    if ($this->start_time == 0) {
                        $html .= '<span>待排期</span></br>';
                    } else {
                        $html .= '<span>' . date('Ymd', $this->start_time) . '-' . date('Ymd', $this->end_time) . '</span></br>';
                    }
                    if ($this->activity_state != mBlindBoxActivity::ACTIVITY_STATE_ONLINE && $this->activity_state != mBlindBoxActivity::ACTIVITY_STATE_DRAFT) {
                        $html .= '</br><span><a href="javascript:;" class="btn btn-default editTime" data-type=""   data-id="' . $this->id . '" >更改排期</a></span></br>';
                    }
                    if ($this->prize_type == mBlindBoxActivity::PRIZE_TYPE_GOODS) {//todo 如果有中奖信息
                        //$html .= '</br><span><a href="javascript:;" class="btn btn-default changeAddress" data-type=""   data-id="' . $this->id . '" >编辑收货地址</a></span>';
                    }
                    $html .= '</div>';
                    return $html;
                })->width(150);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    if ($actions->row->activity_state == mBlindBoxActivity::ACTIVITY_STATE_NORMAL) {
                        $actions->prepend('&nbsp;&nbsp;<a class="fa pass-data" data-state="' . mBlindBoxActivity::ACTIVITY_STATE_PASS . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">通过</a>');
                        $actions->prepend('&nbsp;&nbsp;<a class="fa not-pass-data" data-state="' . mBlindBoxActivity::ACTIVITY_STATE_UN_PASS . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">不通过</a>');
                    } else if ($actions->row->activity_state != mBlindBoxActivity::ACTIVITY_STATE_DEL && $actions->row->activity_state != mBlindBoxActivity::ACTIVITY_STATE_END) {
                        $actions->prepend('&nbsp;&nbsp;<a class="fa del-data" data-state="' . mBlindBoxActivity::ACTIVITY_STATE_DEL . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">取消活动</a>');
                    }

                    // 添加中奖信息列表
                    if (in_array($actions->row->activity_state, [mBlindBoxActivity::ACTIVITY_STATE_ONLINE, mBlindBoxActivity::ACTIVITY_STATE_END])) {
                        $actions->prepend('&nbsp;<a class="fa" target="_blank" href="' . url('/admin/blindBox/winnerList?activity_id=' . $actions->row->id) . '">
                            <span class="glyphicon glyphicon-eye-open" aria-hidden="true">中奖信息</span></a>');
                    }
                    if ($actions->row->activity_state == mBlindBoxActivity::ACTIVITY_STATE_END) {
                        $btnTitle = $actions->row->activity_data ? '编辑数据' : '上传数据';
                        $actions->append('<div class="btn-group download" style="margin-right: 10px">
    <a class="fa fa-bar-chart" href="javascript:layer.open({
                                type: 2,
                                title: \'编辑数据\',
                                maxmin: true,
                                shadeClose: true,
                                shade: 0,
                                area: [\'750px\', \'500px\'],
                                content: \'/admin/blindBox/index/' . $actions->row->id . '/activityData\'
                            });" title="' . $btnTitle . '"><i class="fa"></i><span class="hidden-xs">' . $btnTitle . '</span></a>
</div>');
                    }
                });
            }
        );
        $content->row($gridList);
        return $content
            ->header('审核列表')
            ->description(' ')
            ->breadcrumb(['text' => '审核列表']);
    }

    public function editCoupon(Request $request, Content $content, $id)
    {
        $script = <<<SCRIPT
            $('.has-many-coupon_list-form.fields-group').each(function(){
                var coupon_state=$(this).find('input.coupon_list.coupon_state').val();
                if(coupon_state) {
                    $(this).find('input.form-control.coupon_list.coupon').attr('readonly','readonly');
                    $(this).find('i.fa.fa-pencil.fa-fw').after('&nbsp;'+coupon_state);
                }
            });
SCRIPT;
        Admin::script($script);
        $info = mBlindBoxActivity::getInfoById($id);
        $activityPrizeList = mBlindBoxActivityPrize::getActivityPrizeList($id);
        $prizeList = $activityPrizeList ? $activityPrizeList[$id] : [];
        $info['request_url'] = url()->previous();
        if (count($prizeList) > 1) {
            foreach ($prizeList as $row) {
                if (in_array($row['prize_type'], [mBlindBoxActivityPrize::PRIZE_TYPE_SHOP_COUPON, mBlindBoxActivityPrize::PRIZE_TYPE_GOOD_COUPON])) {
                    $info['coupon_list'][] = [
                        'coupon' => $row['prize_value'],
                        'coupon_state' => $row['prize_state'] == (mBlindBoxActivityPrize::PRIZE_STATE_RECEIVED) ? '已抽中' : ''
                    ];
                }
            }
        } else {
            $info['prize_value'] = $prizeList ? $prizeList[0]['prize_value'] : '';
            $info['prize_state'] = $prizeList ? $prizeList[0]['prize_state'] : 0;
        }
        if (!in_array($info['prize_type'], [mBlindBoxActivity::PRIZE_TYPE_SHOP_COUPON, mBlindBoxActivity::PRIZE_TYPE_GOOD_COUPON])) {
            return $content
                ->header('编辑活动「' . $info['title'] . '」优惠券')
                ->description('')
                ->breadcrumb(
                    ['text' => '审核列表', 'url' => '/admin/blindBox/index'],
                    ['text' => '编辑活动优惠券']
                );
        }
        $info['coupon_count'] = count($prizeList);
        $form = new Form($info);
        $form->hidden('request_url', '');
        $form->text('id', '活动ID')->readonly();
        $form->text('prize_price', '单品价值')->readonly();
        if (count($prizeList) > 1) {
            $form->fieldGroup('coupon_list', '', function ($form) {
                $form->hidden('group_id', '分组id');
                $form->text('coupon', '优惠券码')->required();
                $form->hidden('coupon_state', '状态');
            });
            $form->hidden('coupon_count', '优惠券数量');
            $form->disableSubmit();
        } else {
            if ($info['prize_state'] == mBlindBoxActivityPrize::PRIZE_STATE_RECEIVED) {
                $form->text('prize_value', '优惠券码')->readonly()->prepend('已抽中');
                $form->disableSubmit();
            } else {
                $form->text('prize_value', '优惠券码')->required();
            }
            $form->hidden('coupon_count', '优惠券数量');
        }
        $form->disableReset();
        $form->action('/admin/blindBox/index/changeCoupon');
        if ($info['activity_state'] == mBlindBoxActivity::ACTIVITY_STATE_ONLINE) {
            $form->disableSubmit();
        }
        $content->row($form);
        return $content
            ->header('编辑活动「' . $info['title'] . '」优惠券')
            ->description('')
            ->breadcrumb(
                ['text' => '审核列表', 'url' => url('/admin/blindBox/index')],
                ['text' => '编辑活动优惠券']
            );
    }

    public function changeCoupon(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            $couponList = $request->input('coupon_list', null);
            $couponCount = $request->input('coupon_count', 1);
            $info = $id ? mBlindBoxActivity::getInfoById($id) : [];
            if ($couponCount > 1) {
                if (empty($id) || empty($couponList) || empty($info)) {
                    throw new \Exception('不存在的活动，或则优惠码信息为空');
                }
                $coupon = [];
                foreach ($couponList as $row) {
                    if (!$row['_remove_'] && $row['coupon']) {
                        $coupon[] = $row['coupon'];
                    }
                }
                $coupon = array_unique($coupon);
                $prizeNum = count($coupon);
            } else {
                $prizeValue = $request->input('prize_value', '');
                if (empty($id) || empty($prizeValue) || empty($info)) {
                    throw new \Exception('不存在的活动，或则优惠码信息为空');
                }
                $prizeNum = $info['prize_num'];
                $coupon[] = $prizeValue;
            }
            $prizeTotalPrice = bcmul($prizeNum, $info['prize_price'], 2);
            if ($prizeNum < 1) {
                throw new \Exception('没有任何优惠券码');
            }
            if ($prizeTotalPrice < BlindBox::MIN_PRIZE_TOTAL_PRICE) {
                throw new \Exception('总价值不低于' . BlindBox::MIN_PRIZE_TOTAL_PRICE);
            }
            $activityPrizeList = mBlindBoxActivityPrize::getActivityPrizeList($id);
            if ($activityPrizeList) {
                $activityPrizeList = $activityPrizeList[$id];
                $result = mBlindBoxActivity::action(function () use ($info, $prizeNum, $coupon, $prizeTotalPrice, $activityPrizeList) {
                    $allPrizeValues = array_column($activityPrizeList, 'prize_value');
                    $delPrizeValue = array_diff($allPrizeValues, $coupon);
                    $addPrizeValue = array_diff($coupon, $allPrizeValues);
                    foreach ($activityPrizeList as $row) {
                        if ($row['prize_state'] == mBlindBoxActivityPrize::PRIZE_STATE_RECEIVED) {//如果有奖品被领取了
                            if (in_array($row['prize_value'], $delPrizeValue)) {
                                throw new \Exception('奖品：『' . $row['prize_value'] . '』已经被用户领取,不能删除');
                            }
                        }
                    }
                    $adminId = Admin::user()->id;
                    $data = [
                        'prize_num' => $prizeNum,
                        'prize_stock' => $prizeNum,
                        'prize_total_price' => $prizeTotalPrice,
                        'admin_id' => $adminId
                    ];
                    $result = mBlindBoxActivity::updateData($data, ['id' => $info['id']]);
                    if ($result) {
                        if ($delPrizeValue) {
                            $delWhere = [
                                'prize_value' => $delPrizeValue,
                                'activity_id' => $info['id'],
                                'prize_state' => mBlindBoxActivityPrize::PRIZE_STATE_NORMAL
                            ];
                            $result = mBlindBoxActivityPrize::updateData(['prize_state' => mBlindBoxActivityPrize::PRIZE_STATE_DEL], $delWhere);
                            if (!$result) {
                                Log::debug('编辑奖品失败,删除已有奖品失败#sql:' . json_encode(mBlindBoxActivityPrize::log(), JSON_UNESCAPED_UNICODE));
                                throw  new \Exception('编辑奖品失败');
                            }
                        }
                        foreach ($addPrizeValue as $value) {
                            $addPrizeData = [
                                'activity_id' => $info['id'],
                                'prize_type' => $info['prize_type'],
                                'prize_value' => $value,
                                'prize_state' => mBlindBoxActivityPrize::PRIZE_STATE_NORMAL,
                            ];
                            $result = mBlindBoxActivityPrize::insertData($addPrizeData);
                            if (!$result) {
                                Log::debug('添加奖品失败#sql:' . json_encode(mBlindBoxActivityPrize::log(), JSON_UNESCAPED_UNICODE));
                                throw new \Exception('添加奖品失败');
                            }
                        }
                    } else {
                        Log::debug('编辑优惠券失败#sql:' . json_encode(mBlindBoxActivityPrize::log(), JSON_UNESCAPED_UNICODE));
                        throw new \Exception('编辑优惠券失败');
                    }
                    return true;
                });
            }
            if ($result) {
                $redirectUrl = $request->input('request_url', '');
                $redirectUrl = $redirectUrl ? $redirectUrl : '/admin/blindBox/index';
                $success = new MessageBag([
                    'title' => '修改成功'
                ]);
                return redirect($redirectUrl)->with(compact('success'));
            } else {
                throw new \Exception('修改优惠券信息失败');
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '修改优惠券信息失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function editImg(Request $request, WorkContent $content, $id)
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }
        $info['request_url'] = url()->previous();
        $info['id'] = $id;
        $activityInfo = mBlindBoxActivity::getByWhere(['id' => $id]);
        if ($activityInfo) {
            $form = new Form($info);
            $form->hidden('id', 'id');
            $form->hidden('request_url', '');
            $form->imgUpload('prize_img', '奖品图片', false, ['isGetUrl' => false]);
            $form->action('/admin/blindBox/index/changeImg');
            $desc = '';
            $content->row($form);
        }
        return $content
            ->header('更换奖品图片')
            ->description($desc);
    }

    public function changeImg(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            $prizeImg = $request->input('prize_img', '');
            $prizeImg = $prizeImg ? self::formatImg($prizeImg) : '';
            $adminId = Admin::user()->id;
            if (!$prizeImg) {
                throw new \Exception('图片为空');
            }
            $data = [
                'prize_img' => $prizeImg,
                'admin_id' => $adminId
            ];
            $result = mBlindBoxActivity::updateData($data, ['id' => $id]);
            $redirectUrl = $request->input('request_url', '');
            $redirectUrl = $redirectUrl ? $redirectUrl : '/admin/blindBox/index';
            return redirect($redirectUrl);
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '更换图片失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function editDynamic(Request $request, WorkContent $content, $id)
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }
        $info['request_url'] = url()->previous();
        $info['id'] = $id;
        $activityInfo = mBlindBoxActivity::getByWhere(['id' => $id]);
        if ($activityInfo) {
            $form = new Form($info);
            $form->hidden('id', 'id');
            $form->hidden('request_url', '');
            $form->imgUpload('dynamic_img', '中奖动态图', false, ['imgType' => ImgUrl::APPTYPE_BIZ]);
            $form->action('/admin/blindBox/index/changeDynamic');
            $desc = '';
            $content->row($form);
        }
        return $content
            ->header('更换中奖动态图片')
            ->description($desc);
    }

    public function changeDynamic(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            $dynamicImg = $request->input('dynamic_img', '');
            if (!$dynamicImg) {
                throw new \Exception('动态图片为空');
            }
            $data = [
                'dynamic_img' => $dynamicImg,
            ];
            $result = mBlindBoxActivity::updateData($data, ['id' => $id]);
            $redirectUrl = $request->input('request_url', '');
            $redirectUrl = $redirectUrl ? $redirectUrl : '/admin/blindBox/index';
            return redirect($redirectUrl);;
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '更换动态图片失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function editTime(Request $request, WorkContent $content, $id)
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }
        $info = mBlindBoxActivity::getInfoById($id);
        $info['start_time'] = $info['start_time'] ? date('Y-m-d', $info['start_time']) : '';
        $info['end_time'] = $info['end_time'] ? date('Y-m-d', $info['end_time']) : '';
        $info['expected_time'] = $info['expected_time'] ? date('Y-m-d', $info['expected_time']) : '';
        $form = new Form($info);
        $form->hidden('request_url', '');
        $form->text('id', '活动ID')->readonly();
        $form->select('activity_state', '活动状态')->options(mBlindBoxActivity::$activityStateDesc)->readOnly()->disable();
        $form->date('expected_time', '期望上线时间')->readonly();
        $form->date('start_time', '开始时间');
        $form->date('end_time', '结束时间');
        $form->action('/admin/blindBox/index/changeTime');
        $desc = '';
        if (in_array($info['activity_state'], [mBlindBoxActivity::ACTIVITY_STATE_ONLINE, mBlindBoxActivity::ACTIVITY_STATE_END])) {
            $form->disableSubmit();
            $form->disableReset();
            $desc = '当前状态不支持排期';
        }
        $content->row($form);
        return $content
            ->header('活动「' . $info['title'] . '」排期')
            ->description($desc);
    }

    public function changeTime(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            $startTime = $request->input('start_time', '');
            $endTime = $request->input('end_time', '');
            $startTime = $startTime ? strtotime(date('Y-m-d', strtotime($startTime))) : 0;
            $endTime = $endTime ? strtotime(date('Y-m-d', strtotime($endTime))) + 86399 : 0;
            $info = $id ? mBlindBoxActivity::getInfoById($id) : [];
            if ($startTime >= $endTime) {
                throw new \Exception('开始时间必须小于结束时间');
            }
            if (empty($id) || empty($info)) {
                throw new \Exception('不存在的活动');
            }
            if (in_array($info['activity_state'], [mBlindBoxActivity::ACTIVITY_STATE_ONLINE, mBlindBoxActivity::ACTIVITY_STATE_END])) {
                throw new \Exception('当前状态不支持排期');
            }
            $adminId = Admin::user()->id;
            $data = [
                'start_time' => $startTime,
                'end_time' => $endTime,
                'admin_id' => $adminId
            ];
            $result = mBlindBoxActivity::updateData($data, ['id' => $id]);
            if ($info['activity_state'] == mBlindBoxActivity::ACTIVITY_STATE_PASS) {
                BrandActivityBasic::updateActivityBasic($id, BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX, $info['brand_id'], $info['basic_id'], $startTime, $endTime);
            }
            return redirect('/admin/blindBox/index/' . $id . '/editTime?code=1')->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '活动排期失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function unPass(Request $request, WorkContent $content, $id)
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }
        $info = mBlindBoxActivity::getInfoById($id);
        $info['reason'] = '';
        $form = new Form($info);
        $form->text('id', '活动ID')->readonly();
        $form->text('reason', '不通过原因')->required();
        $form->action('/admin/blindBox/index/unPassPost');
        $content->row($form);
        return $content->header('不通过原因');
    }

    public function unPassPost(Request $request)
    {
        try {
            $id = $request->input('id', 0);
            $reason = $request->input('reason', '');
            if (!$reason) {
                throw new \Exception('请填写不通过原因');
            }
            $adminId = Admin::user()->id;
            $info = mBlindBoxActivity::getInfoById($id, false);
            if (empty($info)) {
                throw new \Exception('不存在的活动信息');
            }
            if (in_array($info['activity_state'], [mBlindBoxActivity::ACTIVITY_STATE_NORMAL])) {
                $result = mBlindBoxActivity::updateData(['activity_state' => mBlindBoxActivity::ACTIVITY_STATE_UN_PASS, 'admin_id' => $adminId], ['id' => $id]);
                $msg = '你所提报的 %s 超级盲盒活动未能通过审核，【%s】';
                $reason = $request->input('reason', '');
                if ($reason) {
                    $msg = sprintf($msg, $info['title'], $reason);
                    \Biz\service\BrandIndex::writeMsg($info['brand_id'], \Biz\model\brandIndex\BrandMsg::MSG_TYPE_OVER, \Biz\model\brandIndex\BrandMsg::MSG_SOURCE_BLIND_BOX, $msg);
                }

                BrandEquityVerificationService::activityRightsRefund($info['brand_id'], $id, BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX, $adminId);

            } else {
                throw new \Exception('当前状态不能操作审核不通过');
            }
            BrandActivityBasic::updateActivityState($id, BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX, $info['basic_id'], BrandActivityBasic::ACTIVITY_STATE_DEL);
            $success = new MessageBag([
                'title' => 'success'
            ]);
            return redirect('/admin/blindBox/index/' . $id . '/unPass?code=1')->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '审核不通过失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function audit(Request $request)
    {
        try {
            $adminId = Admin::user()->id;
            $id = $request->input('id', 0);
            $state = $request->input('state', null);
            if ($id && !is_null($state)) {
                $info = mBlindBoxActivity::getInfoById($id);
                switch ($state) {
                    case mBlindBoxActivity::ACTIVITY_STATE_PASS:
                        if (in_array($info['activity_state'], [mBlindBoxActivity::ACTIVITY_STATE_NORMAL, mBlindBoxActivity::ACTIVITY_STATE_UN_PASS])) {
                            $result = mBlindBoxActivity::updateData(['activity_state' => mBlindBoxActivity::ACTIVITY_STATE_PASS, 'admin_id' => $adminId], ['id' => $id]);
                            $msg = '你所提报的 %s 超级盲盒活动已审核通过，将在 %s-%s 生效，请关注后台通知做后续相应对接';
                            $msg = sprintf($msg, $info['title'], date('Ymd', $info['start_time']), date('Ymd', $info['end_time']));
                            \Biz\service\BrandIndex::writeMsg($info['brand_id'], \Biz\model\brandIndex\BrandMsg::MSG_TYPE_PASS, \Biz\model\brandIndex\BrandMsg::MSG_SOURCE_BLIND_BOX, $msg);
                            if ($result) {
                                BrandActivityBasic::updateActivityBasic($id, BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX, $info['brand_id'], $info['basic_id'], $info['start_time'], $info['end_time']);
                                //用户参与营销活动.超级盲盒
                                \Biz\service\brand\BrandGrowth::levelTaskJoin(0, $info['brand_id']);
                            }
                        } else {
                            throw new \Exception('当前状态不能操作审核通过');
                        }
                        break;
                    case mBlindBoxActivity::ACTIVITY_STATE_DEL:
                        $result = mBlindBoxActivity::updateData(['activity_state' => mBlindBoxActivity::ACTIVITY_STATE_DEL, 'admin_id' => $adminId], ['id' => $id]);
                        BrandActivityBasic::updateActivityState($id, BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX, $info['basic_id'], BrandActivityBasic::ACTIVITY_STATE_DEL);
                        if (in_array($info['activity_state'], [mBlindBoxActivity::ACTIVITY_STATE_NORMAL, mBlindBoxActivity::ACTIVITY_STATE_PASS,
                            mBlindBoxActivity::ACTIVITY_STATE_ONLINE
                        ])) {
                            //活动取消，返还活动次数
                            BrandEquityVerificationService::activityRightsRefund($info['brand_id'], $id, BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX, $adminId);
                        }
                        break;
                }
                $success = [
                    'title' => '操作成功',
                    'code' => 1
                ];
            }
        } catch (\Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }

    public static function activityData(Request $request, WorkContent $content, $id)
    {
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 10);
SCRIPT;
            Admin::script($script);
        }
        $info = mBlindBoxActivity::get(['id', 'title', 'activity_data'], ['id' => $id]);
        $form = new Form($info);
        $form->text('id', '活动id')->readonly();
        $form->text('title', '活动名称')->disable();
        $form->textarea('activity_data', '活动数据')->required();
        $form->action('/admin/blindBox/index/activityDataPost');
        return $content->header('活动数据')
            ->row($form);
    }

    public static function activityDataPost(Request $request)
    {
        $params = $request->all();
        $id = $params['id'] ?? 0;
        $activityData = $params['activity_data'] ?? '';
        try {
            if (empty($id)) {
                throw new \Exception('id为空');
            }
            $res = mBlindBoxActivity::updateData(['activity_data' => $activityData], ['id' => $id]);
            if ($res) {
                $success = new MessageBag([
                    'title' => '保存成功'
                ]);
            } else {
                $error = new MessageBag([
                    'title' => '保存失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
            return redirect("/admin/blindBox/index/'.$id.'/activityData?code=1")->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    private static function getCondition($request)
    {
        $condition['ORDER'] = ['start_time' => 'DESC'];
        if (isset($request['activity_id']) && !empty($request['activity_id'])) {
            $condition['id'] = $request['activity_id'];
            return $condition;
        }
        if (isset($request['start_time']) && strlen(trim($request['start_time'])) > 0) {
            $condition['start_time[>=]'] = strtotime($request['start_time']);
            $condition['start_time[<=]'] = strtotime($request['start_time']) + 86399;
            return $condition;
        }
        if (isset($request['activity_title']) && strlen(trim($request['activity_title'])) > 0) {
            $condition['title[~]'] = trim($request['activity_title']);
        }
        if (isset($request['activity_state']) && strlen($request['activity_state']) > 0 && in_array($request['activity_state'], array_keys(mBlindBoxActivity::$activityStateDesc))) {
            $now = time();
            switch ($request['activity_state']) {
                case mBlindBoxActivity::ACTIVITY_STATE_PASS:
                    $condition['activity_state'] = mBlindBoxActivity::ACTIVITY_STATE_PASS;
                    $condition['OR'] = [
                        'start_time[>]' => $now,
                        'start_time' => 0,
                    ];
                    break;
                case mBlindBoxActivity::ACTIVITY_STATE_ONLINE:
                    $condition['activity_state'] = mBlindBoxActivity::ACTIVITY_STATE_PASS;
                    $condition['start_time[<=]'] = $now;
                    $condition['end_time[>=]'] = $now;
                    break;
                case mBlindBoxActivity::ACTIVITY_STATE_END:
                    $condition['activity_state'] = mBlindBoxActivity::ACTIVITY_STATE_PASS;
                    $condition['end_time[<]'] = $now;
                    $condition['start_time[>]'] = 0;
                    $condition['end_time[>]'] = 0;
                    break;
                default:
                    $condition['activity_state'] = $request['activity_state'];
                    break;
            }
        }
        if (isset($request['brand_id']) && !empty($request['brand_id'])) {
            $condition['brand_id'] = $request['brand_id'];
        } else if (isset($request['brand_name']) && strlen(trim($request['brand_name'])) > 0) {
            $brandIds = mBrand::getBrandByFilter(['brand_name' => $request['brand_name']], 'id');
            if ($brandIds) {
                $condition['brand_id'] = $brandIds;
            } else {
                $condition = null;
            }
        }
        return $condition;
    }

    private function operateScript()
    {
        return <<<SCRIPT
        $('.grid-table').on('click', '.grid-column-copyable', (function (e) {
            var content = $(this).data('content');
            var temp = $('<input>');
            $("body").append(temp);
            temp.val(content).select();
            document.execCommand("copy");
            temp.remove();
            $(this).tooltip('show');
        }));
        
        $('.editTime').unbind('click').click(function() {
            var id = $(this).data('id');
            layer.open({
                type: 2,
                title: '更改排期',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['700px', '600px'],
                content: '/admin/blindBox/index/'+id+'/editTime',
            });
		});
		$('.changeAddress').unbind('click').click(function() {
            var id = $(this).data('id');
            var dataType=$(this).data('type');
            layer.open({
                type: 2,
                title: '更改标签',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['700px', '600px'],
                content: '/admin/brand/wiki/changeTag/'+id+'?type='+dataType,
            });
		});
		
        $('.pass-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var state=$(this).data('state');
            let url = '/admin/blindBox/index/audit'
            let params = {id:id,state:state}
            $.post(url, params , function (result) {
                if (result.code == 1) {
                    layer.msg(result.title);
                    setTimeout(function () {
                        parent.window.location.reload();
                    }, 2000);
                } else {
                    layer.msg(result.title);
                }
            });
        });
        
        $('.not-pass-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var state=$(this).data('state');
            layer.open({
                type: 2,
                title: '不通过原因',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['700px', '600px'],
                content: '/admin/blindBox/index/'+id+'/unPass',
            });
        });
        
        
        $('.del-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var state=$(this).data('state');
            let url = '/admin/blindBox/index/audit'
            let params = {id:id,state:state}
            layer.confirm('确定要取消活动吗？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.title);
                    }
                });
            });
        });
SCRIPT;
    }

    private static function getBlindBoxList($where)
    {
        $where['brand_id[>]'] = 0;
        $list = mBlindBoxActivity::getBlindBoxList($where);
        $activityIds = array_column($list, 'id');
        $activityPrizeList = mBlindBoxActivityPrize::getActivityPrizeList($activityIds);
        $brandIds = array_column($list, 'brand_id');
        $brandIds = array_unique($brandIds);
        $brandInfos = Brand::getBrandInfoByIds4Goods($brandIds);
        $result = [];
        foreach ($list as $id => $row) {
            $prizeList = isset($activityPrizeList[$id]) ? $activityPrizeList[$id] : [];
            $receivedCount = 0;
            $coupon = [];
            foreach ($prizeList as $prizeInfo) {
                if (in_array($prizeInfo['prize_type'], [mBlindBoxActivityPrize::PRIZE_TYPE_SHOP_COUPON, mBlindBoxActivityPrize::PRIZE_TYPE_GOOD_COUPON])) {
                    $coupon[] = $prizeInfo['prize_value'];
                }
                if ($prizeInfo['prize_state'] == mBlindBoxActivityPrize::PRIZE_STATE_RECEIVED) {
                    $receivedCount++;
                }
            }
            $row['brand_name'] = isset($brandInfos[$row['brand_id']]) ? $brandInfos[$row['brand_id']]['name'] : '';
            $row['prize_stock'] = $row['prize_stock'];
            $row['coupon'] = $coupon;
            $result[] = $row;
        }
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $total = mBlindBoxActivity::getBlindBoxCount($where);
        return ['list' => $result, 'total' => $total];
    }

    private static function formatImg($pic_id)
    {
        $pattern = '/(http|https):\/\/([\w.]+\/?)\S*/';
        if (preg_match($pattern, $pic_id) || strpos($pic_id, '//') === 0) {
            $url = $pic_id;
        } else {
            $url = $pic_id ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $pic_id, ImgUrl::IMAGE_SIZE_OP_ORI) : '';
        }
        return $url;
    }

}
